import React, { useEffect, useState } from 'react';
import { Col, Row, Tree, Card, Tag, Pagination, Table, message } from 'antd';
import { useParams } from 'react-router-dom';
import type { DataNode, TreeProps } from 'antd/es/tree';
import type { ColumnsType } from 'antd/es/table';
import { reqDep, reqRegular, reqSchedule } from '@api/hospitalList';
import {
  IdepList,
  IbookingScheduleList,
  IscheduleRule,
  Ischedule
} from '@api/hospitalList/model/hospitalListType';
import Column from 'antd/lib/table/Column';
const treeData: DataNode[] = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leaf',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
      {
        title: 'parent 1-1',
        key: '0-0-1',
        children: [
          {
            title: <span style={{ color: '#1890ff' }}>sss</span>,
            key: '0-0-1-0',
          },
        ],
      },
    ],
  },
];

//表格配置数据
const columns: ColumnsType<Ischedule> = [
  {
    title: '序号',
    render(_, records, index) {
      return index + 1;
    },
    align: 'center',
    width: 80,
  },
  {
    title: '职称',
   dataIndex:'title'
  },
  {
    title: '号源时间',
   dataIndex:'workDate'
  },
  {
    title: '	可预约数',
   dataIndex:'availableNumber'
  },
  {
    title: '	剩余预约数',
   dataIndex:'reservedNumber'
  },
  {
    title: '挂号费（元）',
   dataIndex:'amount'
  },
  {
    title: '擅长技能',
   dataIndex:'skill'
  },
];
export default function HospitalDetail() {
  const { hoscode } = useParams();
  //科室数据状态
  const [depList, SetDepList] = useState<IdepList>([]);
  const [depCodes, setDepCodes] = useState<string[]>([]);
  const [depcode, setDepCode] = useState('');
  //排班规则状态
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(2);
  const [total, setTotal] = useState(0);
  //获取排版规则数据
  const [regularList, setRegularList] = useState<IbookingScheduleList>([]);

  const [scheduleList, setScheduleList] = useState<IscheduleRule>([]);
  //面包屑导航的三个状态
  const [depname, setDepname] = useState('');
  const [hosname, setHosname] = useState('');
  const [workDate, setWorkDate] = useState('');
  useEffect(() => {
    //挂载阶段执行科室管理
    getHosDep();
  }, []);
  async function getHosDep() {
    const result = await reqDep(hoscode as string);
    setDepname(result[0].children[0].depname);

    //第一级禁用
    result.map((item) => (item.disabled = true));
    const codes = result.map((item) => item.depcode);
    // 找到第一个一级科室的第一个二级科室的编码
    let depcode = result[0].children[0].depcode;
    setDepCode(depcode);
    setDepCodes(codes);
    SetDepList(result);
    //层层嵌套，获取完科室再获取排班规则，因为从科室才能获取depcode
    getRugularList(page, pageSize, depcode);
  }

  //排班规则，异步操作，所以需要的参数自己填充，不然会页面呈现数据
  async function getRugularList(
    page: number,
    pageSize: number,
    depcode: string
  ) {
    const result = await reqRegular(page, pageSize, hoscode as string, depcode);
    if(!result.bookingScheduleList.length){
      message.error('当前科室暂无数据')
      setRegularList([])
      setScheduleList([])
      setWorkDate('')
      return
    }
   
    const workDate = result.bookingScheduleList[0]?.workDate;

    setHosname(result.baseMap.hosname);
    setWorkDate(workDate);
    setRegularList(result.bookingScheduleList);
    setTotal(result.total);

    getScheduleRule(depcode, workDate);
  }

  //table数据
  async function getScheduleRule(depcode: string, workDate: string) {
    const result = await reqSchedule(hoscode as string, depcode, workDate);
    setScheduleList(result);
  }
  //tree 提供的函数
  const onSelect: TreeProps['onSelect'] = (selectedKeys, info:any) => {

    //面包屑的功能改变
    setDepname(info.node.depname)
    //排班数据规则发生变化
    getRugularList(1,pageSize,info.node.depcode)
    setPage(1)
    setDepCode(info.node.depcode)
    console.log('selected', selectedKeys, info);
    
  };

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      <Row gutter={20}>
        <Col
          span={5}
          style={{ border: '1px solid #ccc', height: 500, overflow: 'scroll' }}
        >
          <Tree
            onSelect={onSelect}
            expandedKeys={depCodes}
            // 默认选中的节点的key值
            selectedKeys={[depcode]}
            treeData={depList as any}
            fieldNames={{
              title: 'depname',
              key: 'depcode',
            }}
          />
        </Col>
        <Col span={19}>
          {regularList.map((item) => (
            <Tag
              key={item.workDate}
              style={{ marginBottom: 10 }}
              color={item.workDate === workDate ? 'green' : ''}
              onClick={() =>{
                //点击时修改面包屑workDate
                setWorkDate(item.workDate)
                //table数据重新更新
                getScheduleRule(depcode,workDate)

              }}
            >
              <div>
                {item.workDate} {item.dayOfWeek}
              </div>
              <div>
                {item.availableNumber}/{item.reservedNumber}
              </div>
            </Tag>
          ))}

          <Pagination
            current={page}
            showQuickJumper={true}
            total={total}
            pageSize={pageSize}
            pageSizeOptions={[2, 5, 10]}
            onChange={(page, pageSize) => {
              setPage(page);
              setPageSize(pageSize);
              getRugularList(page, pageSize, depcode);
            }}
          ></Pagination>
          <Table dataSource={scheduleList} columns={columns} rowKey={'id'} pagination={false}>
          </Table>
        </Col>
      </Row>
    </Card>
  );
}
